package com.zs.netty.live;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

/**
 * @author madison
 * @description
 * @date 2021/10/21 10:59
 */
public class LiveDecoder extends ReplayingDecoder<LiveDecoder.LiveState> {

    public enum LiveState {
        TYPE,
        LENGTH,
        CONTENT
    }

    private LiveMessage message;

    public LiveDecoder() {
        super(LiveState.TYPE);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        LiveState state = state();
        switch (state) {
            case TYPE -> {
                message = new LiveMessage();
                byte type = in.readByte();
                System.out.println("type:" + type);
                message.setType(type);
                checkpoint(LiveState.LENGTH);
            }
            case LENGTH -> {
                int length = in.readInt();
                message.setLength(length);
                if (length > 0) {
                    checkpoint(LiveState.CONTENT);
                } else {
                    out.add(message);
                    checkpoint(LiveState.TYPE);
                }
            }
            case CONTENT -> {
                byte[] bytes = new byte[message.getLength()];
                in.readBytes(bytes);
                message.setContent(new String(bytes));
                out.add(message);
                checkpoint(LiveState.TYPE);
            }
            default -> {
                throw new IllegalAccessException("invalid state:" + state);
            }
        }
        System.out.println("end state:" + state + " list:" + out);
    }
}
